const Router = require('koa-router')
const { query,constInsert,constUpdate,paging,constructWhere } = require('../db')
const { getRes } = require('../res')
let goods = new Router()


goods.post('/getall_mcnid_byuser', async(ctx) => {
    try {
        let res = await query(`select mcn_id from mcn where user_id =? and content_id is null order by id desc`,ctx.user.id);
        let list = [];
        res.forEach(item => {
            list.push(item.mcn_id);
        });
        ctx.response.body = getRes(0,list);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

goods.post('/getlist', async(ctx) => {
    let orderby = ctx.request.body.orderby;
    let ordertype = ctx.request.body.ordertype;
    let name = ctx.request.body.name;
    let queryObj = {
        "amb_mcn_name":name,
        user_id:ctx.user.id,
        "null_content_id":"0"
    };
    let whereObj = constructWhere(queryObj)
    try {
        let res = await query(`select * from mcn ${whereObj.where}  order by  ${orderby} ${ordertype}`,whereObj.values);
        let obj = getRes(0,res);
        ctx.response.body = obj;
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

goods.post('/save', async(ctx) => {
    let qry = JSON.parse( JSON.stringify( ctx.request.body));
    delete qry.token;
    qry.user_id=ctx.user.id;
    try {
        if(qry.mode=="mcn_add"){
            let queryObj = {
                mcn_id:qry.mcn_id,
                user_id:qry.user_id,
                "null_content_id":"0"
            };
            let whereObj = constructWhere(queryObj);
            let total = await query(`select count(1) as cnt from mcn ${whereObj.where}`,whereObj.values);
            console.log(total);
            if(total[0].cnt>0){
                ctx.response.body = getRes(0,null);
            }else{
                delete qry.mode;
                let res = await constInsert('mcn',qry);
                ctx.response.body = getRes(0,res);
            }
        }else if(qry.mode=="mcn_delete"){
            let queryObj = {
                mcn_id:qry.mcn_id,
                user_id:qry.user_id,
                "null_content_id":"0"
            };
            let whereObj = constructWhere(queryObj);
            let res = await query(`delete from mcn ${whereObj.where}`,whereObj.values);
            ctx.response.body = getRes(0,res);
        }else{
            ctx.response.body = getRes(3,null);
        }
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

module.exports = goods;